package com.muapet.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.muapet.mapper.AdminMapper;
import com.muapet.mapper.PrivilegeMapper;
import com.muapet.model.Admin;
import com.muapet.model.Privilege;
import com.muapet.service.IAdminService;

@Service
public class AdminServiceImpl implements IAdminService {

	private AdminMapper adminMapper;
	private PrivilegeMapper privilegeMapper;

	@Autowired
	public void setAdminMapper(AdminMapper adminMapper) {
		this.adminMapper = adminMapper;
	}

	@Autowired
	public void setPrivilegeMapper(PrivilegeMapper privilegeMapper) {
		this.privilegeMapper = privilegeMapper;
	}

	@Override
	@Transactional(readOnly = true)
	public Admin login(String loginname, String password) {
		Admin admin = new Admin();
		admin.setLoginname(loginname);
		admin.setPassword(password);
		return adminMapper.selectOne(admin);
	}

	@Override
	public Admin findById(Integer id) {
		return adminMapper.selectByPrimaryKey(id);
	}

	@Override
	public Integer addAdmin(Admin admin) {
		adminMapper.insertSelective(admin);
		return admin.getId();
	}

	@Override
	public boolean checkSameLoginname(String loginname) {
		Admin admin = new Admin();
		admin.setLoginname(loginname);
		return adminMapper.selectCount(admin) == 0;
	}

	@Override
	public Integer updateAdmin(Admin admin) {
		return adminMapper.updateByPrimaryKeySelective(admin);
	}

	@Override
	public List<Admin> listAdmins() {
		return adminMapper.selectAll();
	}

	@Override
	public Integer deleteAdmin(Integer id) {
		if (id == 1) {
			return 0;
		}
		return adminMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<Privilege> listPrivilegesInuse() {
		Privilege privilege = new Privilege();
		privilege.setState(Privilege.PRIV_STATE_INUSE);
		return privilegeMapper.select(privilege);
	}

	@Override
	public List<Privilege> listAllPrivileges() {
		return privilegeMapper.selectAll();
	}

	@Override
	public Privilege findPrivilegeById(Integer id) {
		return privilegeMapper.selectByPrimaryKey(id);
	}

	@Override
	public Integer addPrivilege(Privilege privilege) {
		return privilegeMapper.insertSelective(privilege);
	}

	@Override
	public Integer updatePrivilege(Privilege privilege) {
		return privilegeMapper.updateByPrimaryKeySelective(privilege);
	}

	@Override
	public Integer deletePrivilege(Integer id) {
		return privilegeMapper.deleteByPrimaryKey(id);
	}

	@Override
	public boolean checkURL(String url) {
		Privilege privilege = new Privilege();
		privilege.setUrl(url);
		return privilegeMapper.selectCount(privilege) == 0;
	}
}
